/* The default ADC full-scale voltage is 1.1V. To read higher voltages (up to the pin maximum voltage,
 * usually 3.3V) requires setting >0dB signal attenuation for that ADC channel.
 *
 * When VDD_A is 3.3V:
 *
 * - 0dB attenuaton (ADC_ATTEN_DB_0) gives full-scale voltage 1.1V
 * - 2.5dB attenuation (ADC_ATTEN_DB_2_5) gives full-scale voltage 1.5V
 * - 6dB attenuation (ADC_ATTEN_DB_6) gives full-scale voltage 2.2V
 * - 11dB attenuation (ADC_ATTEN_DB_11) gives full-scale voltage 3.9V (see note below)
 *
 * @note The full-scale voltage is the voltage corresponding to a maximum reading (depending on ADC1 configured
 * bit width, this value is: 4095 for 12-bits, 2047 for 11-bits, 1023 for 10-bits, 511 for 9 bits.)
 *
 * @note At 11dB attenuation the maximum voltage is limited by VDD_A, not the full scale voltage.
 *
 * Due to ADC characteristics, most accurate results are obtained within the following approximate voltage ranges:
 *
 * - 0dB attenuaton (ADC_ATTEN_DB_0) between 100 and 950mV
 * - 2.5dB attenuation (ADC_ATTEN_DB_2_5) between 100 and 1250mV
 * - 6dB attenuation (ADC_ATTEN_DB_6) between 150 to 1750mV
 * - 11dB attenuation (ADC_ATTEN_DB_11) between 150 to 2450mV
 */

#include <stdio.h>
#include <stdlib.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/queue.h"
#include "driver/gpio.h"
#include "driver/adc.h"
#include "esp_system.h"
#include "esp_adc_cal.h"

void my_adc_init(void)
{
    int read_raw;
    esp_err_t r;
    // 初始化adc2, 衰减11db
    adc2_config_channel_atten( ADC2_CHANNEL_0, ADC_ATTEN_DB_11 );
    // 
    // vTaskDelay(2 * portTICK_PERIOD_MS);
    // 读值
    r = adc2_get_raw( ADC2_CHANNEL_0, ADC_WIDTH_12Bit, &read_raw);
    if ( r == ESP_OK ) {
        printf("test, adc2 channel %d value is: %d\n", (int)ADC2_CHANNEL_0 , read_raw );
    } else if ( r == ESP_ERR_INVALID_STATE ) {
        printf("%s: ADC2 not initialized yet.\n", esp_err_to_name(r));
    } else if ( r == ESP_ERR_TIMEOUT ) {
        //This can not happen in this example. But if WiFi is in use, such error code could be returned.
        printf("%s: ADC2 is in use by Wi-Fi.\n", esp_err_to_name(r));
    } else {
        printf("%s\n", esp_err_to_name(r));
    }
}

// 读取adc值
int my_adc_get_value(void)
{
    int read_raw;
    double average = 0;
    esp_err_t r;
    char i = 10;
    while(i)
    {
        // 读值
        r = adc2_get_raw( ADC2_CHANNEL_0, ADC_WIDTH_12Bit, &read_raw);
        if ( r != ESP_OK )
        {
            printf("adc2 channel %d adc2_get_raw error\n", (int)ADC2_CHANNEL_0 );
            return 0;
        } 
        else
        {
            average += read_raw / 10.0;
        }
        i--;
    }
    printf("get adc2 channel %d value is: %d\n", (int)ADC2_CHANNEL_0 , read_raw );
    return (int)average;
}
